<?php

namespace app\admin\controller;

use app\admin\model\NoticeNode;
use app\admin\model\Notice;
use think\Controller;
use think\Request;

class HomNotice extends Controller

{
    /***加载首页
     * @return \think\response\View
     */
    public function index(Request $request)
    {

//        $title = $request->param('title');
//        return $title;
        $paginate = [];
        $where = function ($query) use ($request) {
            //按名称
            if ($request->has('title') and $request->param('title') != '') {
                $search = "%" . $request->param('title') . "%";
                $query->where('title', 'like', $search);
                $paginate['title'] = $request->param('title');
            }

            if ($request->param('notice_node_id')) {
                $notice_node_id = $request->param('notice_node_id');

                $query->where('notice_node_id', $notice_node_id);
                $paginate['notice_node_id'] = $notice_node_id;
            }
        };
        $notices = Notice::with('noticeNode')->where($where)->paginate(3,false,
            ['query'=> $paginate]);
        $nodes = NoticeNode::all();
//        return $notices;

        return view('HomNotice/index', compact('notices','nodes'));
    }

    /***加载新增页面
     * @return \think\response\View
     * @throws \think\exception\DbException
     */

    public function add_notice()
    {
        $nodes = NoticeNode::all();
//        return $nodes;
        return view('HomNotice/add_notice', compact('nodes'));
    }

    /***新增通知
     * @param Request $request
     */
    public function save(Request $request)
    {

        $notices = Notice::create($request->param());

        $notices->save();
        return redirect('HomNotice/index');

    }

    /***加载编辑页面
     * @param $id
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($id)
    {

        $nodes = NoticeNode::all();
        $notice = Notice::with('noticeNode')->find($id);
//        return $notice;
        return view('HomNotice/edit', compact('nodes', 'notice'));

    }

    /***保存编辑内容
     * @param Request $request
     * @param $id
     * @return \think\response\Redirect
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */

    public function update(Request $request, $id)
    {
        $notice = Notice::find($id);
        $notice->allowField(true)->save($request->param(), ['id' => $id]);
        return redirect('HomNotice/index');

    }

    public function delete($id)
    {
        Notice::destroy($id);
        return redirect('HomNotice/index');
    }


}